<template>
    <div class="common-layout">
        <el-container>
            <el-header class="header">
                <div class="header-left">知港</div>
                <el-dropdown class="header-right" trigger="click">
                    <span class="el-dropdown-link">
                        {{ username }}
                        <ArrowDown class="arrow-icon" />
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="changePassword">修改密码</el-dropdown-item>
                            <el-dropdown-item @click="logout">退出</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-header>

            <el-container>
                <el-aside class="aside" width="160px">
                    <el-menu :default-active="activeMenu" class="el-menu-vertical" @select="handleMenuSelect"
                        background-color="#f5f9f0" text-color="#303133" active-text-color="var(--primary-color)">
                        <template v-for="item in sideMenu" :key="item.index">
                            <el-sub-menu v-if="item.children" :index="item.index">
                                <template #title>{{ item.label }}</template>
                                <el-menu-item v-for="sub in item.children" :key="sub.index" :index="sub.index">{{
                                    sub.label
                                }}</el-menu-item>
                            </el-sub-menu>
                            <el-menu-item v-else :index="item.index">{{ item.label }}</el-menu-item>
                        </template>
                    </el-menu>
                </el-aside>

                <el-main class="main">
                    <router-view />
                </el-main>
            </el-container>
        </el-container>
        <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px" @close="handlePasswordDialogClose">
            <el-form :model="passwordForm" :rules="passwordFormRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" type="password" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handlePasswordDialogClose">取消</el-button>
                <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { changePasswordAPI } from '@/api/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const username = computed(() => userStore.nickname)
const role = userStore.role

const allMenu = [
    { index: '/harborSpace/home', label: '首页', roles: ['super_admin', 'user'], children: undefined },
    { index: '/harborSpace/user', label: '用户中心', roles: ['super_admin'], children: undefined },
    {
        index: '/harborSpace/trace',
        label: '航迹',
        roles: ['super_admin', 'user'],
        children: [
            { index: '/harborSpace/trace/task', label: '任务列表', children: undefined },
            { index: '/harborSpace/trace/archive', label: '归档列表', children: undefined }
        ]
    },
    { index: '/harborSpace/smart', label: '智汇', roles: ['super_admin', 'user'], children: undefined },
    { index: '/harborSpace/user/profile', label: '个人资料', roles: ['super_admin', 'user', 'visitor'], children: undefined }
]

const sideMenu = computed(() =>
    allMenu.filter(item => item.roles.includes(role))
)

const activeMenu = ref(route.path === '/harborSpace' ? '/harborSpace/home' : route.path)

watch(
    () => route.path,
    (newPath) => {
        activeMenu.value = newPath === '/harborSpace' ? '/harborSpace/home' : newPath
    }
)


const logout = () => {
    userStore.logout();
    router.push('/login');
}

function handleMenuSelect(index: any) {
    activeMenu.value = index
    router.push(index)
}

/* 修改密码 */
const showPasswordDialog = ref(false)
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})
const passwordFormRef = ref()
const passwordFormRules = {
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value !== passwordForm.value.newPassword) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ]
}

const changePassword = () => {
    showPasswordDialog.value = true
}

const handlePasswordSubmit = () => {
    passwordFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            try {
                await changePasswordAPI({
                    oldPassword: passwordForm.value.oldPassword,
                    newPassword: passwordForm.value.newPassword
                })
                showPasswordDialog.value = false
                ElMessage.success({
                    message: '密码修改成功',
                    duration: 1000
                })
                setTimeout(() => {
                    userStore.logout();
                    router.push('/login');
                }, 1000)
            } catch (e) {
                console.error('密码修改失败')
            } finally {
                passwordForm.value.oldPassword = ''
                passwordForm.value.newPassword = ''
                passwordForm.value.confirmPassword = ''
            }
        }
    })
}

const handlePasswordDialogClose = () => {
    showPasswordDialog.value = false
    passwordForm.value.oldPassword = ''
    passwordForm.value.newPassword = ''
    passwordForm.value.confirmPassword = ''
}

</script>


<style scoped>
.common-layout {
    height: 100vh;
    background-color: #f0f2f5;
    display: flex;
    flex-direction: column;
}

.header {
    height: 60px;
    background-color: var(--bg-color-base, #ffffff);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    border-bottom: 1px solid var(--border-color-base, #d3e4c7);
    flex-shrink: 0;
}

.header-left {
    font-size: 22px;
    font-weight: bold;
    color: var(--primary-color);
    letter-spacing: 2px;
}

/* 给 header-right 设置宽度和居中，防止内容过窄换行 */
.header-right {
    cursor: pointer;
    color: var(--text-color-secondary);
    font-weight: 500;
    user-select: none;
    min-width: 80px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

/* 关键：用户名和箭头水平排列且不换行 */
.el-dropdown-link {
    display: flex;
    align-items: center;
    white-space: nowrap;
    /* 防止换行 */
    font-size: 14px;
    color: var(--text-color-secondary);
    min-width: 60px;
    /* 适当调整 */
}

.arrow-icon {
    margin-left: 6px;
    width: 12px;
    height: 12px;
    color: var(--text-color-secondary);
}

.aside {
    background-color: var(--bg-color-lighter);
    height: calc(100vh - 60px);
    border-right: 1px solid var(--border-color-base);
    box-shadow: 2px 0 6px rgba(0, 0, 0, 0.03);
}

.el-menu-vertical {
    border-right: none;
}

.main {
    background-color: var(--bg-color-base);
    padding: 20px;
    height: calc(100vh - 60px);
    overflow-y: auto;
}
</style>
